package com.hnust.root.service.forword.wx;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hnust.root.common.util.ComUtil;
import com.hnust.root.dao.entity.domain.forward.Comment;
import com.hnust.root.dao.entity.domain.forward.Topic;
import com.hnust.root.dao.entity.domain.forward.UserMessage;
import com.hnust.root.dao.mapper.wx.TopicMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hnust.root.dao.mapper.wx.CommentMapper;

import java.util.Date;

@Service
public class CommentService {
    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private WxUserInfoService userInfoService;

    @Autowired
    private TopicMapper topicMapper;

    @Autowired
    private MessageService messageService;

    /**
     * 通过话题ID获取评论
     * @param page
     * @param topicId
     * @return
     */
    public IPage<Comment> getCommentByTopicId(IPage<Comment> page, int topicId) {
        page = commentMapper.selectPage(page, new QueryWrapper<Comment>()
                .eq("topic_id", topicId)
                .orderByDesc("create_time"));
        if (page != null) {
            page.getRecords().forEach(comment -> {
                comment.setUserInfo(userInfoService.getUserInfoByOpenId(comment.getOpenId()));
            });
        }
        return page;
    }

    /**
     * 添加评论
     * @param comment
     * @return
     */
    public boolean addComment(Comment comment) {
        topicMapper.addCommentCount(comment.getTopicId());
        addUserMessage(comment);
        return ComUtil.DBisSuccess(commentMapper.insert(comment));
    }

    //用户评论时增加用户消息
    private void addUserMessage(Comment comment) {
        UserMessage userMessage = new UserMessage();
        userMessage.setUpdatedAt(new Date());
        userMessage.setFlag(false);
        userMessage.setContentType("comment");
        Topic topic = topicMapper.selectById(comment.getTopicId());
        userMessage.setToOpenId(topic.getOpenId());
        userMessage.setFromOpenId(comment.getOpenId());
        userMessage.setTopicId(comment.getTopicId());
        messageService.addUserMessage(userMessage);
    }

    public Comment getCommentById(int id) {
        return commentMapper.selectById(id);
    }

    //通过话题ID删除评论数据
    public void deleteComentByTopicId(int topicId) {
        commentMapper.delete(new QueryWrapper<Comment>().eq("topic_id", topicId));
    }
}
